package cn.edu.ncut.cs.springboot.petmanagementsystem.controller;

import cn.edu.ncut.cs.springboot.petmanagementsystem.common.PageResult;
import cn.edu.ncut.cs.springboot.petmanagementsystem.common.Result;
import cn.edu.ncut.cs.springboot.petmanagementsystem.dto.PetInformationDto;
import cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.Pet;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.PetService;
import cn.edu.ncut.cs.springboot.petmanagementsystem.vo.PetInformationVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/sale-pets")
@Tag(name = "待售宠物管理模块")
public class SalePetController {

    @Autowired
    private PetService petService;
    
    @Autowired
    private cn.edu.ncut.cs.springboot.petmanagementsystem.mapper.PetMapper petMapper;
    
    // ==================== 管理后台接口 ====================
    
    @Operation(summary = "管理员查询待售宠物列表（支持动态查询）")
    @GetMapping({"/admin/list", "/admin/sale-pets/list"})
    // @PreAuthorize("hasRole('ADMIN')")  // 如需启用权限，取消注释
    public PageResult<PetInformationVo> getAdminSalePetList(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "宠物名称") @RequestParam(required = false) String petName,
            @Parameter(description = "分类ID") @RequestParam(required = false) Long categoryId,
            @Parameter(description = "品种") @RequestParam(required = false) String breed,
            @Parameter(description = "销售状态") @RequestParam(required = false) Integer saleStatus,
            @Parameter(description = "最低售价") @RequestParam(required = false) java.math.BigDecimal minPrice,
            @Parameter(description = "最高售价") @RequestParam(required = false) java.math.BigDecimal maxPrice,
            @Parameter(description = "最低折扣(%)") @RequestParam(required = false) Integer minDiscount,
            @Parameter(description = "最高折扣(%)") @RequestParam(required = false) Integer maxDiscount,
            @Parameter(description = "最少浏览量") @RequestParam(required = false) Integer minViewCount,
            @Parameter(description = "最少点赞数") @RequestParam(required = false) Integer minLikeCount,
            @Parameter(description = "是否推荐") @RequestParam(required = false) Boolean isRecommended,
            @Parameter(description = "是否热销") @RequestParam(required = false) Boolean isHot,
            @Parameter(description = "上架开始日期") @RequestParam(required = false) String startDate,
            @Parameter(description = "上架结束日期") @RequestParam(required = false) String endDate,
            @Parameter(description = "排序字段") @RequestParam(required = false) String orderBy,
            @Parameter(description = "排序方向") @RequestParam(required = false, defaultValue = "desc") String order
    ) {
        try {
            log.info("管理员查询待售宠物 - petName: {}, categoryId: {}, saleStatus: {}", petName, categoryId, saleStatus);
            log.info("筛选条件 - 价格: [{}-{}], 折扣: [{}-{}], 浏览量: {}, 点赞: {}, 推荐: {}, 热销: {}", 
                     minPrice, maxPrice, minDiscount, maxDiscount, minViewCount, minLikeCount, isRecommended, isHot);
            
            com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<Pet> queryWrapper = 
                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
            
            // 1-3. 基础查询
            if (org.springframework.util.StringUtils.hasText(petName)) {
                queryWrapper.like(Pet::getPetName, petName);
            }
            if (categoryId != null) {
                queryWrapper.eq(Pet::getCategoryId, categoryId);
            }
            if (org.springframework.util.StringUtils.hasText(breed)) {
                queryWrapper.like(Pet::getBreed, breed);
            }
            
            // 4. 销售状态（映射到宠物状态）
            if (saleStatus != null) {
                queryWrapper.eq(Pet::getPetStatus, saleStatus);
            } else {
                // 默认只查询待售和已预定的宠物
                queryWrapper.in(Pet::getPetStatus, java.util.Arrays.asList(1, 4));
            }
            
            // 5-6. 价格范围（忽略0值）
            if (minPrice != null && minPrice.compareTo(java.math.BigDecimal.ZERO) > 0) {
                queryWrapper.ge(Pet::getPrice, minPrice);
            }
            if (maxPrice != null && maxPrice.compareTo(java.math.BigDecimal.ZERO) > 0) {
                queryWrapper.le(Pet::getPrice, maxPrice);
            }
            
            // 7. 折扣范围（计算字段 - 需要 original_price 字段存在）
            // 折扣 = (price / original_price) * 100
            // 只有当minDiscount或maxDiscount大于0时才添加条件
            if ((minDiscount != null && minDiscount > 0) || (maxDiscount != null && maxDiscount > 0)) {
                // 使用SQL计算折扣百分比
                int minDiscountValue = (minDiscount != null && minDiscount > 0) ? minDiscount : 0;
                int maxDiscountValue = (maxDiscount != null && maxDiscount > 0) ? maxDiscount : 100;
                // 注意：需要确保original_price不为0，且price和original_price都存在
                queryWrapper.apply("original_price IS NOT NULL AND original_price > 0 AND " +
                                 "(price * 100.0 / original_price) BETWEEN {0} AND {1}",
                                 minDiscountValue, maxDiscountValue);
                log.info("使用折扣范围筛选: {}% - {}%", minDiscountValue, maxDiscountValue);
            }
            
            // 8-9. 浏览量和点赞数（忽略0值）
            if (minViewCount != null && minViewCount > 0) {
                queryWrapper.ge(Pet::getViewCount, minViewCount);
            }
            if (minLikeCount != null && minLikeCount > 0) {
                queryWrapper.ge(Pet::getLikeCount, minLikeCount);
            }
            
            // 10-11. 推荐和热销（如果Pet表有这些字段）
            // 注意：如果Pet表没有isRecommended和isHot字段，可以通过其他方式判断
            // 例如：推荐 = viewCount > 100 或 likeCount > 20
            // 热销 = viewCount > 200 或 最近30天有销售记录
            if (isRecommended != null) {
                if (isRecommended) {
                    // 通过浏览量或点赞数判断是否推荐
                    queryWrapper.and(wrapper -> 
                        wrapper.ge(Pet::getViewCount, 100)
                               .or()
                               .ge(Pet::getLikeCount, 20)
                    );
                    log.info("筛选推荐宠物（浏览量>=100 或 点赞数>=20）");
                } else {
                    // 不推荐：浏览量<100 且 点赞数<20
                    queryWrapper.and(wrapper -> 
                        wrapper.lt(Pet::getViewCount, 100)
                               .and(w -> w.lt(Pet::getLikeCount, 20))
                    );
                }
            }
            if (isHot != null) {
                if (isHot) {
                    // 通过浏览量判断是否热销
                    queryWrapper.ge(Pet::getViewCount, 200);
                    log.info("筛选热销宠物（浏览量>=200）");
                } else {
                    queryWrapper.lt(Pet::getViewCount, 200);
                }
            }
            
            // 12. 日期范围
            if (org.springframework.util.StringUtils.hasText(startDate)) {
                queryWrapper.ge(Pet::getCreateTime, startDate + " 00:00:00");
            }
            if (org.springframework.util.StringUtils.hasText(endDate)) {
                queryWrapper.le(Pet::getCreateTime, endDate + " 23:59:59");
            }
            
            // 13. 排序
            if (org.springframework.util.StringUtils.hasText(orderBy)) {
                boolean isAsc = "asc".equalsIgnoreCase(order);
                switch (orderBy.toLowerCase()) {
                    case "price":
                        queryWrapper.orderBy(true, isAsc, Pet::getPrice);
                        break;
                    case "viewcount":
                        queryWrapper.orderBy(true, isAsc, Pet::getViewCount);
                        break;
                    case "likecount":
                        queryWrapper.orderBy(true, isAsc, Pet::getLikeCount);
                        break;
                    case "updatetime":
                        queryWrapper.orderBy(true, isAsc, Pet::getUpdateTime);
                        break;
                    default:
                        queryWrapper.orderByDesc(Pet::getUpdateTime);
                }
            } else {
                // 默认排序：推荐优先，然后按更新时间倒序
                queryWrapper.orderByDesc(Pet::getUpdateTime);
            }
            
            // 分页查询
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<Pet> page = 
                    new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageNum, pageSize);
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<Pet> result = 
                    petMapper.selectPage(page, queryWrapper);
            
            log.info("管理员查询待售宠物结果 - 总记录数: {}, 当前页: {}, 总页数: {}", 
                     result.getTotal(), result.getCurrent(), result.getPages());
            
            // 转换为VO
            java.util.List<PetInformationVo> voList = result.getRecords().stream()
                    .map(pet -> {
                        PetInformationVo vo = petService.getPetById(pet.getId());
                        return vo;
                    })
                    .filter(vo -> vo != null)
                    .collect(java.util.stream.Collectors.toList());
            
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<PetInformationVo> voPage = 
                    new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(result.getCurrent(), result.getSize(), result.getTotal());
            voPage.setRecords(voList);
            
            return PageResult.success(voPage);
        } catch (Exception e) {
            log.error("管理员查询待售宠物失败", e);
            return PageResult.pageError("查询失败: " + e.getMessage());
        }
    }
    
    // ==================== 用户端接口 ====================

    @Operation(summary = "添加待售宠物信息")
    @PostMapping
    public Result<?> createSalePet(@RequestBody java.util.Map<String, Object> request) {
        try {
            PetInformationDto dto = convertRequestToDto(request);
            dto.setPetStatus(1);
            boolean success = petService.createPet(dto);
            return success ? Result.success("添加成功") : Result.error("添加失败");
        } catch (Exception e) {
            log.error("添加待售宠物失败", e);
            return Result.error("添加失败: " + e.getMessage());
        }
    }

    private PetInformationDto convertRequestToDto(java.util.Map<String, Object> request) {
        PetInformationDto dto = new PetInformationDto();
        
        if (request.get("name") != null) dto.setPetName(request.get("name").toString());
        
        // 如果前端未传 categoryId，默认设置为 1
        if (request.get("categoryId") != null) {
            dto.setCategoryId(Long.parseLong(request.get("categoryId").toString()));
        } else {
            dto.setCategoryId(1L);
        }
        
        if (request.get("breed") != null) dto.setBreed(request.get("breed").toString());
        if (request.get("age") != null) dto.setAge(Integer.parseInt(request.get("age").toString()));
        
        // 性别转换：公->1, 母->2
        if (request.get("gender") != null) {
            String gender = request.get("gender").toString();
            dto.setGender("公".equals(gender) || "1".equals(gender) ? 1 : 2);
        }
        
        if (request.get("price") != null) dto.setPrice(new java.math.BigDecimal(request.get("price").toString()));
        if (request.get("originalPrice") != null) dto.setOriginalPrice(new java.math.BigDecimal(request.get("originalPrice").toString()));
        if (request.get("description") != null) dto.setDescription(request.get("description").toString());
        if (request.get("mainImage") != null) dto.setMainImage(request.get("mainImage").toString());
        
        return dto;
    }

    @Operation(summary = "修改待售宠物资料")
    @PutMapping("/{id}")
    public Result<?> updateSalePet(
            @Parameter(description = "宠物ID") @PathVariable Long id,
            @RequestBody PetInformationDto dto) {
        try {
            dto.setId(id);
            petService.UpdatePetInformation(dto);
            return Result.success("更新成功");
        } catch (Exception e) {
            log.error("更新待售宠物失败", e);
            return Result.error("更新失败: " + e.getMessage());
        }
    }

    @Operation(summary = "查询所有待售宠物信息")
    @GetMapping({"", "/list"})
    public PageResult<PetInformationVo> getSalePetList(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNO,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "宠物名称") @RequestParam(required = false) String petName,
            @Parameter(description = "宠物类型") @RequestParam(required = false) String petType,
            @Parameter(description = "性别") @RequestParam(required = false) Integer gender) {
        try {
            log.info("收到查询待售宠物列表请求 - pageNO: {}, pageSize: {}, petName: {}, petType: {}, gender: {}", 
                    pageNO, pageSize, petName, petType, gender);
            IPage<PetInformationVo> page = petService.getPetsByCondition(pageNO, pageSize, petName, petType, gender);
            log.info("查询待售宠物列表成功 - 总数: {}, 当前页: {}", page.getTotal(), page.getCurrent());
            return PageResult.success(page);
        } catch (Exception e) {
            log.error("查询待售宠物列表失败", e);
            return PageResult.pageError("查询失败: " + e.getMessage());
        }
    }

    @Operation(summary = "查看指定待售宠物详情")
    @GetMapping({"/detail/{id}", "/{id}"})
    public Result<?> getSalePetDetail(@Parameter(description = "宠物ID") @PathVariable Long id) {
        try {
            PetInformationVo pet = petService.getPetById(id);
            if (pet == null) {
                return Result.error("宠物不存在");
            }
            return Result.success(pet);
        } catch (Exception e) {
            log.error("获取待售宠物详情失败", e);
            return Result.error("获取详情失败");
        }
    }

    @Operation(summary = "更新销售状态（上架、下架、已售）")
    @PutMapping("/{id}/status")
    public Result<?> updateSaleStatus(
            @Parameter(description = "宠物ID") @PathVariable Long id,
            @RequestBody java.util.Map<String, Integer> request) {
        Integer status = request.get("status");
        try {
            PetInformationDto dto = new PetInformationDto();
            dto.setId(id);
            dto.setPetStatus(status);
            petService.UpdatePetInformation(dto);
            return Result.success("更新状态成功");
        } catch (Exception e) {
            log.error("更新销售状态失败", e);
            return Result.error("更新状态失败: " + e.getMessage());
        }
    }

    @Operation(summary = "删除待售宠物信息")
    @DeleteMapping("/{id}")
    public Result<?> deleteSalePet(@Parameter(description = "宠物ID") @PathVariable Long id) {
        try {
            boolean success = petService.deletePetById(id);
            return success ? Result.success("删除成功") : Result.error("删除失败");
        } catch (Exception e) {
            log.error("删除待售宠物失败", e);
            return Result.error("删除失败: " + e.getMessage());
        }
    }
}
